//
//  homeNextViewController.m
//  CleanerAir_Project
//
//  Created by 胡浩 on 16/5/10.
//  Copyright © 2016年 Beijing Colin El Internet. All rights reserved.
//

#import "homeNextViewController.h"
#import "GoodsModel.h"
#import "GoodsCategory.h"
#import "MJExtension.h"
#import "MenuItemCell.h"
#import "LeftCell.h"
#import "HTTPManager.h"
#import "marketModel.h"


#define ZXColor(r,g,b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
@interface homeNextViewController ()<UITableViewDelegate,UITableViewDataSource,MenuItemCellDelegate>

@property (nonatomic, strong) UITableView   *leftTableView;
@property (nonatomic, strong) UITableView   *rightTableView;
@property (nonatomic, strong) NSMutableArray       *dataArray;
@property (nonatomic, assign) BOOL          isRelate;

@end

@implementation homeNextViewController
static NSString * const cellID = @"MenuItemCell";
static NSString * const ListCellID = @"DetailListCell";



- (void)viewDidLoad {
    [super viewDidLoad];
//    self.tabBarController.tabBar.hidden=YES;
      self.titlelabel.text=@"商场信息";
     self. titlelabel.font = [UIFont boldSystemFontOfSize:18];
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(-5, 13, 45, 18)];
    [leftButton addTarget:self action:@selector(fanhui) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"返回.png"] forState:UIControlStateNormal];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
  
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    CGRect viewBounds = self.view.bounds;
    float navBarHeight = self.navigationController.navigationBar.frame.size.height + 20;
    viewBounds.size.height = ([[UIScreen mainScreen] bounds].size.height) - navBarHeight;
    self.view.bounds = viewBounds;
    
    [self leftTableView];
    [self rightTableView];
//    [self loadData];
    
    [self showIndicator:@"正在加载数据，请稍候..."];
    [self path];

    

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
 
}

//返回到地图界面
-(void)fanhui{

    [self.navigationController popViewControllerAnimated:YES];

}



//左侧tableview
- (UITableView *)leftTableView {
    if (nil == _leftTableView) {
        _leftTableView =  [[UITableView alloc] initWithFrame:CGRectMake(0, 216, MAIN_WIDTH*0.2 , MAIN_HEIGHT -280)];
        _leftTableView.backgroundColor = [UIColor whiteColor];
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_leftTableView];
    }
    return _leftTableView;
    
}
//右侧tabview
- (UITableView *)rightTableView {
    if (nil == _rightTableView) {
        _rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(MAIN_WIDTH * 0.2, 216, MAIN_WIDTH*0.8 , self.view.bounds.size.height-220)];
        _rightTableView.backgroundColor = [UIColor whiteColor];
        _rightTableView.delegate = self;
        _rightTableView.dataSource = self;
        //_rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_rightTableView registerNib:[UINib nibWithNibName:NSStringFromClass([MenuItemCell class]) bundle:nil] forCellReuseIdentifier:cellID];
        [self.view addSubview:_rightTableView];
    }
    return _rightTableView;
}



#pragma mark dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == _leftTableView) {
        return 1;
    } else if (tableView == _rightTableView) {
        return [_dataArray count];
    } else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //NSDictionary *item = [_dataArray objectAtIndex:section];
    GoodsCategory *goodsCategory = _dataArray[section];
    if (tableView == _leftTableView) {
        return _dataArray.count;
    } else if (tableView == _rightTableView) {
        //return [[item objectForKey:@"goodsArray"] count];
        return goodsCategory.goodsArray.count;
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _leftTableView) {
        static NSString *CellIdentifier = @"Cell";
        
        LeftCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"LeftCell" owner:self options:nil] lastObject];
            
            cell.backgroundColor = ZXColor(240, 240, 240);
            UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
            selectedBackgroundView.backgroundColor = [UIColor whiteColor];
            cell.selectedBackgroundView = selectedBackgroundView;
            
            // 左侧示意条
            UIView *liner = [[UIView alloc] initWithFrame: CGRectMake(0, cell.bounds.size.width/8.2, 3, MAIN_HEIGHT/24)];
            liner.backgroundColor = [UIColor redColor];
            [selectedBackgroundView addSubview:liner];
        }
        
        GoodsCategory *goodsCategory = _dataArray[indexPath.row];
        cell.IndexesLabel.text = goodsCategory.name;
        cell.IndexesLabel.tag=100;
        
        return cell;
    } else if (tableView == _rightTableView) {
        
        MenuItemCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        cell.delegate = self;
        
        GoodsCategory *goodsCategory = _dataArray[indexPath.section];
        GoodsModel *goods = goodsCategory.goodsArray[indexPath.row];
        
        cell.goods = goods;
        UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        selectedBackgroundView.backgroundColor = [UIColor whiteColor];
        cell.selectedBackgroundView = selectedBackgroundView;
        
        return cell;
        
    } else {
        return nil;
    }
}

#pragma mark delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _leftTableView) {
        return MAIN_HEIGHT/14 ;
    } else if (tableView == _rightTableView) {
        return MAIN_HEIGHT/4.5;
    } else {
        return 50;
    }
}

//返回每一个组头的高度，如果想达到有那种效果则一定要做这个操作
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == _rightTableView) {
        return 30;
    } else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (tableView == _rightTableView) {
        return 0.01;
    } else {
        return 0;
    }
}

//返回组头部的那块View
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
  
    if (tableView == _rightTableView) {
        UIView *view = [[UIView alloc]init];
        view.frame = CGRectMake(0, 0, tableView.frame.size.width, 30);
        view.backgroundColor = ZXColor(240, 240, 240);
        [view setAlpha:0.4];
        UILabel *label = [[UILabel alloc]initWithFrame:view.bounds];
        //NSDictionary *item = [_dataArray objectAtIndex:section];
        GoodsCategory *goodsCategory = [_dataArray objectAtIndex:section];
        NSString *title = goodsCategory.goodsCategoryDesc;
        [label setText:[NSString stringWithFormat:@"%@",title]];
        [view addSubview:label];
        label.font = [UIFont systemFontOfSize:15];
        label.textAlignment=NSTextAlignmentCenter;
        return view;
    } else {
      
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //左边tableView
    if (tableView == _leftTableView) {
        _isRelate =  NO;
        [self.leftTableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
        
        //点击了左边的cell，让右边的tableView跟着滚动
        [self.rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexPath.row] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    } else if (tableView == _rightTableView) {
        [_rightTableView deselectRowAtIndexPath:indexPath animated:NO];
        
        NSLog(@"点击这里可以跳到详情页面");
    }
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if (_isRelate) {
        NSInteger topCellSection = [[[tableView indexPathsForVisibleRows] firstObject] section];
        if (tableView == _rightTableView) {
            [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:topCellSection inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
        }
    }
}

- (void)tableView:(UITableView *)tableView didEndDisplayingFooterView:(UIView *)view forSection:(NSInteger)section {
    if (_isRelate) {
        NSInteger topCellSection = [[[tableView indexPathsForVisibleRows] firstObject] section];
        if (tableView == _rightTableView) {
            [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:topCellSection inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
        }
    }
}

#pragma mark - UISCrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
   
    _isRelate = YES;
  
}



#pragma mark ---------解析
-(void)path{
       __weak __typeof(self) weakSelf = self;
    
    [HTTPManager get:[NSString stringWithFormat:@"%@/Api/test/index?tid=1&id=%@",urlHeader,self.userID] success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary*dic=[responseObject objectForKey:@"date"];
        marketModel*model1=[[marketModel alloc]init];
        model1.name=dic[@"name"];
        model1.title=dic[@"title"];
        model1.hot_pic=dic[@"hot_pic"];
        model1.top_pic=dic[@"top_pic"];
        NSLog(@"%@",model1.name);
        
        NSArray*arr=dic[@"date"];
       
       _dataArray = [GoodsCategory objectArrayWithKeyValuesArray:arr];
        [weakSelf hideIndicator];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
        [weakSelf.HeadImage sd_setImageWithURL:[NSURL URLWithString:model1.top_pic] placeholderImage:[UIImage imageNamed:@"顶部占位图.png"]];
                                            
            weakSelf.HeadTitle.text=model1.name;
            
        });
        
        [self.leftTableView reloadData];
        [self.rightTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
         [weakSelf hideIndicator];
    }];

  
    

   

}

-(NSMutableArray *)dataArray{

    if (_dataArray==nil) {
        _dataArray=[[NSMutableArray alloc]init];
    }

    return _dataArray;
}








    









@end
